// pages/Users/EditUsersPage.jsx
import { UpdateUser, ForgotPassword } from "api/mutations";
import { User } from "api/queries";
import Box from "components/atoms/Box";
import Loader from "components/atoms/Loader";
import ConfirmAlert from "libs/confirmAlert";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { useMutation, useQuery, useQueryClient } from "react-query";
import { useParams, useNavigate } from "react-router-dom";
import { useAuth } from 'contexts/AuthContext';
import UsersForm from "./UsersForm";
import QueryDebugLogger from "components/debugging/QueryDebugLogger";
import { 
  Grid,
  Typography,
  Button,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogContentText,
  DialogActions,
  Paper,
  Divider,
  Box as MuiBox
} from '@mui/material';

const EditUsersPage = ({ showQueryLogger = false }) => {
  const { user } = useAuth();
  const navigate = useNavigate();
  const { t } = useTranslation();
  const { userId } = useParams();
  const [editedUser, setEditedUser] = useState(null);
  const [resetDialogOpen, setResetDialogOpen] = useState(false);
  const queryClient = useQueryClient();

  // eslint-disable-next-line no-unused-vars
  const { isLoading, data } = useQuery(
    ["User", user.accountId],
    () => User(userId),
    {
      retry: false,
      onSuccess: (data) => {
        if (data.data.accountOwner) {
          navigate("/users");
        } else {
          setEditedUser(data.data);
        }
      },
    }
  );

  const updateUserMutate = useMutation(UpdateUser, {
    onSuccess: () => {
      queryClient.invalidateQueries(["Users", user.accountId]);
      queryClient.invalidateQueries(["User", user.accountId]);
    },
  });

  // Reset password mutation
  const resetPasswordMutate = useMutation(ForgotPassword, {
    onSuccess: () => {
      ConfirmAlert.success(t("resetPassword.linkSent", "Password reset link has been sent to the user's email"));
      setResetDialogOpen(false);
    },
    onError: (error) => {
      if (error.response?.data?.errors?.length > 0) {
        ConfirmAlert.error(error.response.data.errors[0].message);
      } else if (typeof error.response?.data === 'string') {
        ConfirmAlert.error(error.response.data);
      } else {
        ConfirmAlert.error(t("resetPassword.error", "Failed to send password reset link"));
      }
      setResetDialogOpen(false);
    }
  });

  const onSubmit = async (data) => {
    // No longer removing email as we've modified the backend to accept it
    delete data.password; // Still remove password field to prevent validation errors
    try {
      const response = await updateUserMutate.mutateAsync({
        userId: userId,
        data: data,
      });
      if (response) {
        ConfirmAlert.success(t("updateUsersPage.userUpdated"));
        navigate("/users");
      }
    } catch (error) {
      if (error.response?.data?.errors?.length > 0) {
        ConfirmAlert.error(error.response.data.errors[0].message);
      } else if (typeof error.response?.data === 'string') {
        ConfirmAlert.error(error.response.data);
      } else {
        ConfirmAlert.error("An error occurred");
      }
    }
  };

  // Handle sending password reset link
  const handleSendResetLink = async () => {
    if (!editedUser?.email) return;
    
    try {
      await resetPasswordMutate.mutateAsync({
        email: editedUser.email
      });
    } catch (error) {
      // Error handling is done in the mutation callbacks
    }
  };

  // Create query objects for the debug logger
  const queryDebugData = [
    {
      name: "User Query",
      isLoading: isLoading,
      isError: !!data?.error,
      error: data?.error,
      data: data?.data
    },
    {
      name: "Update User Mutation",
      isLoading: updateUserMutate.isLoading,
      isError: updateUserMutate.isError,
      error: updateUserMutate.error,
      data: updateUserMutate.data
    },
    {
      name: "Reset Password Mutation",
      isLoading: resetPasswordMutate.isLoading,
      isError: resetPasswordMutate.isError,
      error: resetPasswordMutate.error,
      data: resetPasswordMutate.data
    }
  ];

  if (isLoading) {
    return <Loader />;
  }

  return (
    <Grid container spacing={3}>
      {/* Password Reset Section - Above the form */}
      {editedUser && (
        <Grid item xs={12}>
          <Paper 
            elevation={0} 
            sx={{ 
              p: 3,
              mb: 2,
              display: 'flex', 
              flexDirection: 'column', 
              alignItems: 'center',
              border: '1px solid #e0e0e0',
              borderRadius: '8px'
            }}
          >
            <Typography variant="h6" gutterBottom>
              {t("resetPassword.title", "Password Management")}
            </Typography>
            <Divider sx={{ width: '100%', mb: 3 }} />
            <MuiBox sx={{ display: 'flex', justifyContent: 'center', width: '100%' }}>
              <Button
                variant="contained"
                color="primary"
                sx={{ minWidth: 250 }}
                onClick={() => setResetDialogOpen(true)}
                disabled={resetPasswordMutate.isLoading}
              >
                {resetPasswordMutate.isLoading 
                  ? t("resetPassword.sending", "Sending...") 
                  : t("resetPassword.sendLink", "Send Password Reset Link")}
              </Button>
            </MuiBox>
          </Paper>
        </Grid>
      )}
      
      {/* User Edit Form */}
      <Grid item xs={12}>
        <Box
          header={
            <Typography component="h1">
              {t("updateUsersPage.updatedUser")}
            </Typography>
          }
          body={
            editedUser && <UsersForm user={editedUser} onSubmit={onSubmit} showEmail={true} />
          }
        />
      </Grid>
      
      {/* Confirmation Dialog */}
      <Dialog
        open={resetDialogOpen}
        onClose={() => !resetPasswordMutate.isLoading && setResetDialogOpen(false)}
      >
        <DialogTitle>
          {t("resetPassword.confirmTitle", "Send Password Reset Link?")}
        </DialogTitle>
        <DialogContent>
          <DialogContentText>
            {t("resetPassword.confirmMessage", 
              `Are you sure you want to send a password reset link to ${editedUser?.email}? The user will receive an email with instructions to reset their password.`)}
          </DialogContentText>
        </DialogContent>
        <DialogActions>
          <Button 
            onClick={() => setResetDialogOpen(false)} 
            color="primary"
            disabled={resetPasswordMutate.isLoading}
          >
            {t("resetPassword.cancel", "Cancel")}
          </Button>
          <Button 
            onClick={handleSendResetLink} 
            color="primary" 
            variant="contained"
            disabled={resetPasswordMutate.isLoading}
          >
            {resetPasswordMutate.isLoading 
              ? t("resetPassword.sending", "Sending...") 
              : t("resetPassword.confirm", "Send")}
          </Button>
        </DialogActions>
      </Dialog>
      
      {/* Add the query debug logger component */}
      <QueryDebugLogger 
        queries={queryDebugData} 
        isVisible={showQueryLogger} 
      />
    </Grid>
  );
};

export default EditUsersPage;